<template>
  <div class="container">
    <div v-if="patient">
      <h2>患者全景视图</h2>

      <div class="header">
        <div class="patient-info">
          <div class="info-item">
            <div class="info-label">姓名</div>
            <div class="info-value">{{ patient.name }} <span class="tag">{{ patient.status }}</span></div>
          </div>
          <div class="info-item">
            <div class="info-label">性别</div>
            <div class="info-value">{{ patient.gender }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">年龄</div>
            <div class="info-value">{{ patient.age }}岁</div>
          </div>
          <div class="info-item">
            <div class="info-label">联系电话</div>
            <div class="info-value">{{ patient.phone }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">病历号</div>
            <div class="info-value">{{ patient.medical_record_number }}</div>
          </div>
        </div>
      </div>


      <div class="row" style="margin-top: 20px;">
        <div class="col">
          <div class="card">
            <div class="card-header">
              <div @click="toRecord" class="card-title">就诊记录</div>
              <div>...</div>
            </div>
            <div class="card-body">
              <div class="record-item" v-for="(record, index) in patient.disease_records"
                   :key="index">
                <div class="record-date">{{ formatDate(record.date) }}</div>
                <div class="record-content">
                  <div class="record-title-wrapper">
                  <b>{{ ['首次就诊', '急诊就医', '复诊就医'][index] }}</b>
                    <img src="@/assets/personal-center/book.png" class="record-book-icon">
                  </div>
                  <p>{{ record.description }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!--实验检查结果-->
        <div @click="toLaboratortReport" class="col">
          <div class="card">
            <div class="card-header">
              <div class="card-title">实验室检验结果</div>
              <div>...</div>
            </div>
            <div class="card-body">
              <div>血尿酸</div>
              <div class="chart">
                <div ref="laboratoryRef" style="width: 100%; height: 100%;"></div>
              </div>
              <div class="record-content">
                <b>血尿酸浓度</b>
                <div style="display: flex; justify-content: space-between;">
                  <span>{{ formatDate(patient.lab_results.blood_uric_acid.date) }}</span>
                  <span>{{ patient.lab_results.blood_uric_acid.value }}
                    {{ patient.lab_results.blood_uric_acid.unit }}
                    <span
                      :style="getBloodUricAcidStyle(patient.lab_results.blood_uric_acid.value)">
        {{ getBloodUricAcidText(patient.lab_results.blood_uric_acid.value) }}</span></span>
                </div>
              </div>
              <div class="record-content">
                <b>肌酐</b>
                <div style="display: flex; justify-content: space-between;">
                  <span>{{ formatDate(patient.lab_results.creatinine.date) }}</span>
                  <span>{{ patient.lab_results.creatinine.value }}
                    {{ patient.lab_results.creatinine.unit }}
                    <span
                      :style="getCreatinineStyle(patient.lab_results.creatinine.value, patient.gender)">
        {{ getCreatinineText(patient.lab_results.creatinine.value, patient.gender) }}</span></span>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>

      <div class="row">
        <!--影像检查结果-->
        <div @click="toImageCheck" class="col">
          <div class="card">
            <div class="card-header">
              <div class="card-title">影像检查结果</div>
              <div>...</div>
            </div>
            <div class="card-body">
              <div class="record-item" v-for="(image, index) in patient.imaging_results"
                   :key="index">
                <div class="record-content">
                  <div class="image-header-wrapper">
                  <b>{{ image.type }}</b>
                    <div class="image-right-group">
                    <img src="@/assets/personal-center/computer.png"
                         class="image-computer-icon"
                         v-if="['CT','肾脏B超'].includes(image.type)">
<!--                      <div style="text-align: right;">{{ formatDate(image.date) }}</div>-->
                  </div>
                  </div>
                  <p class="image-result">{{ image.result }}</p>
                  <div style="text-align: right;">{{ formatDate(image.date) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="col">
          <div @click="toFollowUpRecord" class="card">
            <div class="card-header">
              <div>
                <div class="card-title">随访计划</div>
                <div style="color: #1e65f7;">{{ patient.follow_up_plan.followup_type ? patient.follow_up_plan.followup_type.join(","):"" }}</div>
              </div>
              <div>...</div>
            </div>
            <div class="card-body">
              <div class="appointment">
                <div class="appointment-time">下次随访日期：</div>
                <div>{{ patient.follow_up_plan.next_follow_up }}</div>
              </div>

              <div class="record-item" v-for="(follow, index) in patient.follow_up_records"
                   :key="index">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <div style="display: flex; align-items: center;">
                  <span>{{ formatDate(follow.date) }}</span>
                    <img src="@/assets/personal-center/chat.png" class="arrow-icon">
                </div>
                  <span class="status">{{ follow.status }}</span>
                </div>
                <div class="record-content">{{ follow.description }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue'
import * as echarts from 'echarts'
import {getPatientById} from '@/demo-data/data/patients.js';
import {useRouter, useRoute} from 'vue-router'

const router = useRouter()  // 用于编程式导航
const route = useRoute()    // 用于获取当前路由信息

// 新增方法
const formatDate = (dateStr) => {
  return dateStr.replace(/(\d{4})-(\d{2})-(\d{2})/, '$1年$2月$3日')
}

//血压图表
const chartRef = ref(null)
let chartInstance = null

//实验室检查结果图表
const laboratoryRef = ref(null)

let laboratoryInstance = null
// 初始化图表
const initLaboratoryChart = () => {
  if (!laboratoryRef.value) return;

  laboratoryInstance = echarts.init(laboratoryRef.value);

  const option = {
    title: {
      text: '',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: '#7581BD',
          width: 1
        }
      },
      formatter: '{b}<br/>{a}: {c}'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data:patient.value.blood_uric_acid_trend.data.map(item => item.time),
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#999'
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#eee'
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '数据值',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#0770FF',
          borderColor: '#fff',
          borderWidth: 2
        },
        lineStyle: {
          width: 3,
          color: '#0770FF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(7, 112, 255, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(7, 112, 255, 0.1)'
            }
          ])
        },
        data: patient.value.blood_uric_acid_trend.data.map(item => item.value),
        markPoint: {
          data: [
            {type: 'max', name: '最大值'},
            {type: 'min', name: '最小值'}
          ]
        },
        markLine: {
          data: [{type: 'average', name: '平均值'}]
        }
      }
    ]
  };

  laboratoryInstance.setOption(option);
};

// 响应式调整图表大小
const resizeChart = () => {
  chartInstance?.resize()
  laboratoryInstance.resize()
}

// 修正数据初始化结构
const patient = ref({
  disease_records: [],
  imaging_results: [],
  lab_results: {
    blood_uric_acid: {  // 添加默认结构
      date: '',
      value: 0,
      unit: '',
      reference_range: ''
    },
    creatinine: {  // 添加默认结构
      date: '',
      value: 0,
      unit: '',
      reference_range: ''
    }
  },
  follow_up_plan: {
    next_follow_up: ''  // 添加默认值
  },
  follow_up_records: []
})
const loading = ref(true);

onMounted(() => {
  //根据路由传入的患者id查询某个患者的本页数据
  if (route.query.patientId) {
    patient.value = getPatientById(route.query.patientId);
    initLaboratoryChart()
    window.addEventListener('resize', resizeChart)
    console.log(patient.value, "patient.value")
  }
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  chartInstance?.dispose()
})

//跳转到就诊记录页面
function toRecord() {
  router.push({
    path: 'record',
    query: {
      patientId: route.query.patientId
    }
  })
}

//跳转到影像检查结果页面
function toImageCheck() {
  router.push({
    path: 'image-check',
    query: {
      patientId: route.query.patientId
    }
  })
}

//跳转到实验室检查结果页面
function toLaboratortReport() {
  router.push({
    path: 'laboratory-report',
    query: {
      patientId: route.query.patientId
    }
  })
}

//跳转到随访记录页面
function toFollowUpRecord() {
  router.push({
    path: 'follow-up-record',
    query: {
      patientId: route.query.patientId
    }
  })
}


// 血尿酸浓度
function getBloodUricAcidText(value) {
  if (value == 420) {
    return "正常"
  } else if (value > 420) {
    return "偏高"
  } else {
    return "偏低"
  }
}
// 新增样式获取方法
function getBloodUricAcidStyle(value) {
  return {
    color: value === 420 ? '#67C23A' : '#d71345',
    fontWeight: 500
  }
}

// 肌酐(血肌酐)参考值范围:
// 男性: 70.0-115.0 μmol/L
// 女性: 44.0-80.0 μmol/L
function getCreatinineText(value, gender) {
  const isNormal = checkCreatinineNormal(value, gender)
  if (isNormal) return "正常";

  const isMale = gender === "男";
  const range = isMale ? { min: 70, max: 115 } : { min: 44, max: 80 };
  return value < range.min ? "偏低" : "偏高";
}

// 肌酐样式方法
function getCreatinineStyle(value, gender) {
  const isNormal = checkCreatinineNormal(value, gender)
  return {
    color: isNormal ? '#67C23A' : '#d71345',
    fontWeight: 500
  }
}
// 新增肌酐正常判断方法
function checkCreatinineNormal(value, gender) {
  const isMale = gender === "男";
  const maleRange = { min: 70, max: 115 };
  const femaleRange = { min: 44, max: 80 };
  const range = isMale ? maleRange : femaleRange;
  return value >= range.min && value <= range.max;
}

// 血肌酐的正常值为：男 70.0—115.0µmol/L，女  44.0-80.0µmol/L。


</script>
<style scoped>
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f5f7fa;
  color: #333;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 15px;
}

.patient-photo {
  width: 70px;
  height: 70px;
  background-color: #ddd;
  border-radius: 5px;
  margin-right: 20px;
}

.patient-info {
  display: flex;
  flex-wrap: wrap;
  flex-grow: 1;
}

.info-item {
  margin-right: 40px;
  margin-bottom: 10px;
}

.info-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.info-value {
  font-size: 14px;
  font-weight: bold;
}

.button {
  background-color: #1e65f7;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.card {
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
  height: 100%;
  cursor: pointer;
}

.arrow-icon {
  width: 30px;  /* 根据实际图片尺寸调整 */
  height: 30px; /* 保持图片比例 */
  margin-left: 8px;
  transition: transform 0.2s;
  object-fit: contain;  /* 保持图片比例 */
  vertical-align: middle;  /* 确保垂直对齐 */
}

.record-item:hover .arrow-icon {
  transform: translateX(3px);
}
/* 就诊记录标题布局 */
.record-title-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
/* 添加/修改样式 */
.image-header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 6px;
}

.image-right-group {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.record-book-icon {
  width: 30px;
  height: 30px;
  opacity: 0.8;
  margin-right: 10px; /* 控制右侧间距 */
}
.image-result {
  margin: 5px 0 0px 0;
  line-height: 1.5;
}
/* 影像检查标题布局 */
.image-title-wrapper {
  display: flex;
  align-items: center;
  gap: 8px; /* 控制图标与文字的间距 */
}

.image-computer-icon {
  width: 30px;
  height: 30px;
  margin-right: 15px; /* 新增左边距 */
  opacity: 0.9;
}


/* 书本图标样式 */
.record-book-icon {
  //width: 18px;
  //height: 18px;
  opacity: 0.8;
  margin-left: 15px; /* 控制右侧间距 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eaeaea;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
}

.card-body {
  padding: 15px;
}

.record-item {
  border-bottom: 1px solid #eaeaea;
  padding: 15px 0;
}

.record-date {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.record-content {
  font-size: 14px;
}

.chart {
  height: 200px;
  margin: 15px 0;
  background-color: #f9f9f9;
  border: 1px solid #eaeaea;
  border-radius: 4px;
}

.row {
  display: flex;
  margin: 0 -10px;
}

.col {
  flex: 1;
  padding: 0 10px;
  margin-bottom: 20px;
}

.tag {
  display: inline-block;
  background-color: #e6f3ff;
  color: #1e65f7;
  padding: 2px 8px;
  border-radius: 2px;
  font-size: 12px;
  margin-right: 5px;
}

.appointment {
  background-color: #f0f8ff;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 10px;
}

.appointment-time {
  font-weight: bold;
  margin-bottom: 5px;
}

.status {
  display: inline-block;
  color: #00a854;
  font-size: 12px;
  margin-left: 10px;
}
</style>
